package com.alibaba.citrus.cr.common.util;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.meshflow.dto.runtime.FlowMessage;
import com.alibaba.lattice2.epoch.meshflow.service.MeshFlowService;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Huang gen(kenfeng)
 * @description 根据traceId获取请求内容
 * @Since 2021-12-22-11:50
 **/

public class SAPRequestUtils {
    private static MeshFlowService meshFlowService;
    static {
        meshFlowService = SpringContextUtil.getBean(MeshFlowService.class);
    }

    public static Map<String,Object> getSAPRequestByTraceId(String traceId) {

        FlowMessage flowMessage = buildFlowMessage(traceId);
        FlowMessage outputMessage = meshFlowService.process(flowMessage);
        if(null != outputMessage && null != outputMessage.getBody()) {
            Map<String,Object> resultMap = (Map<String, Object>)outputMessage.getBody().get("sapRequest");
            return resultMap;
        }
        return null;
    }

    private static FlowMessage buildFlowMessage(String traceId){
        FlowMessage flowMessage= new FlowMessage();
        flowMessage.setAppCode("api_adaptor");
        Map<String,Object> body = new HashMap<>();
        body.put("traceId",traceId);
        flowMessage.setBody(body);
        flowMessage.setFlowCode("getSAPRequestByTraceId");
        flowMessage.setMetadataType("api");
        return flowMessage;
    }
    public static Map<String,Object> retryExteralMatrial(String traceId,String bodyStr) {

        FlowMessage flowMessage = buildMaterialBody(traceId,bodyStr);
        FlowMessage outputMessage = meshFlowService.process(flowMessage);
        if(null != outputMessage && null != outputMessage.getBody()) {
            Map<String,Object> resultMap = (Map<String, Object>)outputMessage.getBody().get("sapRequest");
            return resultMap;
        }
        return null;
    }
    private static FlowMessage buildMaterialBody(String traceId,String bodyStr){
        FlowMessage flowMessage= new FlowMessage();
        flowMessage.setAppCode("epoch");
        Map<String,Object> body = new HashMap<>();
        //如果boydStr为空，才根据traceId查相应的body。 现在有body  traceId可忽略
        body.put("traceId",traceId);
        body.put("appCode","api_adaptor");
        body.put("flowCode","externalSyncMaterial");
        body.put("body", getMap(bodyStr));

        flowMessage.setBody(body);
        flowMessage.setFlowCode("retryApiIntegration");
        flowMessage.setMetadataType("api");
        return flowMessage;
    }
    public static Map<String,Object> getMap(String bodyStr){
        return JSONObject.parseObject(bodyStr,Map.class);
    }

}
